<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="任免类型">
        <el-select
          v-model="queryParams.electType"
          placeholder="请选择任免类型"
          clearable
        >
          <el-option
            :value="item.dictValue"
            :label="item.dictLabel"
            :key="index"
            v-for="(item, index) in electTypeOptions"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="提请任免部门">
        <el-select
          v-model="queryParams.submitDepartmentId"
          placeholder="请选择提请任免部门"
          clearable
        >
          <el-option
            :value="item.value"
            :label="item.label"
            :key="index"
            v-for="(item, index) in submitDepartmentOptions"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="姓名">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="会议名称">
        <el-input
          v-model="queryParams.conferenceName"
          placeholder="请输入会议名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任免时间">
        <el-date-picker
          v-model="queryParams.electTime"
          type="daterange"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          :style="{ width: '100%' }"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          clearable
        ></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="importFile"
          >导入</el-button
        >
      </el-col>
    </el-row>

    <el-table :height="tableHeight" v-loading="loading" :data="dataList">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="姓名" align="center" prop="name" />
      <el-table-column label="原单位" align="center" prop="originPosition" />
      <el-table-column label="原职务" align="center" prop="originDepartment" />
      <el-table-column
        label="任免类型及提请任免部门"
        width="260"
        align="center"
        prop="electDepartment"
      />
      <el-table-column label="会议名称" align="center" prop="conferenceName" />
      <el-table-column
        label="任免时间"
        align="center"
        prop="electTime"
        width="180"
      />

      <el-table-column
        label="操作"
        align="center"
        width="120"
        fixed="right"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-row :gutter="15" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="success"
                plain
                icon="el-icon-edit"
                size="mini"
                @click="handleUpdate(scope.row)"
                >修改</el-button
              >
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="danger"
                plain
                icon="el-icon-delete"
                size="mini"
                @click="handleDelete(scope.row)"
                >删除</el-button
              >
            </el-col>
            <!-- <el-col :span="1.5">
              <el-button
                type="danger"
                plain
                icon="el-icon-delete"
                size="mini"
                @click="toView(scope.row)"
                >查看</el-button
              >
            </el-col> -->
          </el-row>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改岗位对话框 -->
    <el-dialog
      :before-close="beforeClose"
      :title="title"
      :visible.sync="visible"
      width="1050px"
      append-to-body
    >
      <register
        :openType="openType"
        :visible="visible"
        :row="row"
        @goBack="visible = false"
        @callback="callback"
      />
    </el-dialog>
    <!-- 文件导入的弹窗  -->
    <el-dialog
      title="导入"
      :visible.sync="importDialogVisible"
      width="500px"
      append-to-body
    >
      <el-form>
        <el-form-item label-width="120">
          <el-row>
            <el-col :span="8"></el-col>
            <el-col :span="16" style="margin-left: 10rem">
              <file-upload url="/system/election/importData"></file-upload>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label-width="120">
          <el-col :span="8"></el-col>
          <el-col :span="16" style="margin-left: 10rem">
            <el-button type="text" disabled>模板-选举任免.xlsx</el-button>
            <el-button type="text" @click="download">【点击下载】</el-button>
          </el-col>
        </el-form-item>
      </el-form>
      <template slot="footer">
        <el-button type="primary" @click="importDialogVisible = false"
          >取消</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  deptList,
  electionList,
  electionDelete,
  importTemplate,
} from "@/api/register/appoint";
import { listData } from "@/api/system/dict/data";
import Register from "../register/index";
import FileUpload from "@/components/FileUpload3";
import axios from "axios";
import { getToken } from "@/utils/auth";
export default {
  name: "Post",
  components: {
    Register,
    FileUpload,
  },
  dicts: ["sys_normal_disable"],
  data() {
    return {
      tableHeight: "500", // 表格的高度
      // 导入文件的弹窗
      importDialogVisible: false,
      // 打开查看、修改的弹窗
      visible: false,
      openType: "", // 判断当前是编辑 edit 状态，还是查看 view 状态
      row: {}, // 打开弹窗，当前回显的一行数据
      Options: [
        {
          label: "选项一",
          value: 1,
        },
        {
          label: "选项二",
          value: 2,
        },
      ],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      dataList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        postName: [
          { required: true, message: "岗位名称不能为空", trigger: "blur" },
        ],
        postCode: [
          { required: true, message: "岗位编码不能为空", trigger: "blur" },
        ],
        postSort: [
          { required: true, message: "岗位顺序不能为空", trigger: "blur" },
        ],
      },
      // 1、任免类型下拉框
      electTypeOptions: [],
      // 4、提请任免部门
      submitDepartmentOptions: [],
    };
  },
  created() {
    this.getOptions();
    this.getList();
  },
  mounted() {
    this.$nextTick(() => {
      this.getFixedHeight();
    });
    window.addEventListener("resize", this.getFixedHeight);
  },
  methods: {
    getFixedHeight() {
      this.tableHeight = window.innerHeight - 348;
    },
    // 获取任免类型、提请任免部门下拉框
    getOptions() {
      // 任免类型
      let page = {
        pageNum: 1,
        pageSize: 10,
      };
      let queryParams1 = {
        ...page,
        // 任免类型
        dictType: "app_add_remove_type",
      };
      listData(queryParams1).then((response) => {
        this.electTypeOptions = response.rows;
      });
      // 提请任免部门
      deptList().then((res) => {
        this.submitDepartmentOptions = res.data.map((item) => {
          let obj = {
            value: item.deptId,
            label: item.deptName,
          };
          return obj;
        });
      });
    },
    /** 查询岗位列表 */
    getList() {
      let startTime = "",
        endTime = "";
      if (this.queryParams.electTime) {
        startTime = this.queryParams.electTime[0];
        endTime = this.queryParams.electTime[1];
      }
      let queryParams = JSON.parse(JSON.stringify(this.queryParams));
      let params = {
        ...queryParams,
        startTime,
        endTime,
      };

      if (params.electTime) {
        delete params.electTime[0];
        delete params.electTime[1];
      }
      electionList(params)
        .then((res) => {
          //  electTypeOptions: [],
          // 4、提请任免部门
          // submitDepartmentOptions: [],
          this.total = res.total;
          this.dataList = res.rows.map((item) => {
            let electTypeName = "",
              submitDepartmentName = "";
            let electTypeNameArr = this.electTypeOptions.filter(
              (item2) => item2.dictValue == item.electType
            );
            if (electTypeNameArr.length) {
              electTypeName = electTypeNameArr[0].dictLabel;
            }
            let submitDepartmentNameArr = this.submitDepartmentOptions.filter(
              (item2) => item2.value == item.submitDepartmentId
            );
            if (submitDepartmentNameArr.length) {
              submitDepartmentName = submitDepartmentNameArr[0].label;
            }
            item.electDepartment = electTypeName + submitDepartmentName;
            return item;
          });
          this.loading = false;
        })
        .catch((err) => {
          // 请求失败也不要一直loading
          this.loading = false;
          this.dataList = [
            {
              name: "姓名",
              originPosition: "原单位-999",
              originDepartment: "原职务-4444",
              electDepartment: "",
              conferenceName: "会议名称",
              electTime: "2019-07-24 05:32:33",
              // 任免类别
              electDepartment: "全国人大",
              // 任免书编号
              electDocumentNo: "666666666",
              sex: 0,
              nationality: "0",
              birthplace: "富足县里",
              phoneNo: "45668885656",
              documentNo: "文号44444",
              // 任免类型
              electType: "2",
              // 界次
              electionId: 108,
              // 提请任免部门
              submitDepartmentId: 104,
              id: 9999,
              // 文件路径
              filePath:
                "/opt/app/uploadPath/avatar/2024/01/07/链接_20240107194458A024.txt",
            },
          ];
          console.log("err", err);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        postId: undefined,
        postCode: undefined,
        postName: undefined,
        postSort: 0,
        status: "0",
        remark: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      // this.resetForm("queryForm");
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
      };
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.postId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      // 打开查看的对话框
      this.openType = "edit";
      this.title = "任免登记";
      this.row = row;
      this.visible = true;
    },
    /** 提交按钮 */
    submitForm: function () {},
    /** 删除按钮操作 */
    handleDelete(row) {
      console.log("row", row);
      electionDelete([row.id]).then((res) => {
        this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.getList();
        });
        // if (res.code == 200) {
        //   this.$message({
        //     type: "success",
        //     message: "删除成功",
        //   });
        // }
      });
    },
    /** 导出按钮操作 */
    handleExport() {},
    // 查看
    toView(row) {
      // 打开查看的对话框
      this.openType = "view";
      this.title = "查看";
      this.row = row;
      this.visible = true;
    },
    // 弹窗关闭之前，清理弹窗回显的值
    beforeClose(done) {
      this.row = {};
      done();
    },
    importFile() {
      this.importDialogVisible = true;
    },
    downloadFile(data) {
      // 创建一个Blob对象，表示要下载的文件内容
      const fileContent = new Blob([data]);
      // 创建一个可以下载文件的链接
      const downloadLink = document.createElement("a");
      downloadLink.href = URL.createObjectURL(fileContent);
      downloadLink.download = "example.xlsx"; // 设置下载文件的名称
      // 触发点击事件，开始下载文件
      downloadLink.click();
    },
    download() {
      // const response = await axios({
      //   method: 'post',
      //   url: '/dev-api//system/election/importTemplate',
      //   responseType: 'blob',
      //   headers: {
      //     // 添加你的请求头
      //     Authorization: "Bearer " + getToken(),
      //     'Custom-Header': 'CustomValue', // 添加自定义请求头
      //   },
      // });
      axios
        .post(
          "/dev-api/system/election/importTemplate",
          {},
          {
            headers: {
              // 添加你的请求头
              Authorization: "Bearer " + getToken(),
              // 'Custom-Header': 'CustomValue', // 添加自定义请求头
            },
          }
        )
        .then((response) => {
          this.downloadFile(response.data);
        });

      // 下载数据导入的模板
      // importTemplate().then((res) => {
      //   // console.log(";res2222", res);
      //   this.downloadFile(res)
      // });
    },
    // 作用是关闭弹窗
    callback() {
      this.visible = false;
      // 重新查询列表
      this.handleQuery();
    },
  },
};
</script>
